package com.news.servlet;


import com.news.common.BaseServlet;
import com.news.common.CommonResult;
import com.news.common.ServletResp;
import com.news.dao.impl.UmsUserDaoImpl;
import com.news.entity.Admin;
import com.news.entity.Article;
import com.news.entity.User;
import com.news.entity.VerifyCode;
import com.news.enums.Role;
import com.news.service.impl.UmsUserServiceImpl;
import com.news.utils.JsonUtils;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @Author:weiming
 * @Date:2021/3/24
 */
@WebServlet("/admin/*")
public class LoginServlet  extends BaseServlet{

    private UmsUserServiceImpl umsUserService = new UmsUserServiceImpl();
    private UmsUserDaoImpl userDao = new UmsUserDaoImpl();
    public void doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int  userId = 0;
        String userName = request.getParameter("userName");
        String passWord = request.getParameter("passWord");
        String roleStr = request.getParameter("role");
        String code = request.getParameter("code");
        Integer role = Integer.valueOf(roleStr);
        if (role == Role.Admin.getRoleCode()){
            Admin admin = new Admin();
            admin.setUserName(userName);
            admin.setPassWord(passWord);
            userId = umsUserService.login(admin);
        }else if (role == Role.User.getRoleCode()){
            User user = new User();
            user.setUserName(userName);
            user.setPassWord(passWord);
            userId = umsUserService.userLogin(user);
        }
        String codeSession = (String) request.getSession().getAttribute("code");
        System.out.println("验证码"+codeSession);
        if (!codeSession.equalsIgnoreCase(code)){
            ServletResp.resp(response, CommonResult.failed("验证码有误"));
            return;
        }

        if (userId != 0){
             request.getSession().setAttribute("userName", userName);
             request.getSession().setAttribute("role", role);
            request.getSession().setAttribute("userId", userId);
             ServletResp.resp(response, CommonResult.success());
        }else {
            ServletResp.resp(response, CommonResult.failed("登录失败，账号密码有误!"));
        }

    }


    public void toLogin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.getRequestDispatcher("front/page/login/login.html").forward(request, response);
    }

    public void toIndex(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Integer role = (Integer) request.getSession().getAttribute("role");
        if (role == null){
            response.sendRedirect("admin?method=toLogin");
            return;
        }
        if (Role.Admin.getRoleCode()!=role || role == null){
            response.sendRedirect("admin?method=toLogin");
            return;
        }
        request.getRequestDispatcher("front/index.html").forward(request, response);
    }

    public void doLogOut(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.getSession().removeAttribute("userName");
        request.getSession().removeAttribute("userId");
        request.getSession().removeAttribute("role");
        ServletResp.resp(response, CommonResult.success("注销成功"));
    }


    public void toRegist(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.getRequestDispatcher("front/page/login/regist.html").forward(request, response);
    }

    /**
     * 普通用户注册
     * @param request
     * @param response
     */
    public void doRegist(HttpServletRequest request, HttpServletResponse response)  {
        String reqBody = JsonUtils.getJson(request);
        User user = JsonUtils.fromJson(reqBody, User.class);
        int result = userDao.regist(user);
        if (result == 0){
            ServletResp.resp(response, CommonResult.failed("注册失败"));
        }else{
            ServletResp.resp(response, CommonResult.success("注册成功"));
        }
    }

    /**
     * 检查用户名是否重复
     * @param request
     * @param response
     */
    public void checkUsername(HttpServletRequest request, HttpServletResponse response){
            String userName = request.getParameter("userName");
        int result = userDao.checkUsername(userName);
        if (result == 1){
            ServletResp.resp(response, CommonResult.success("用户名可用"));
        }else {
            ServletResp.resp(response, CommonResult.failed("用户名已存在"));
        }
    }

    public void getCode(HttpServletRequest request, HttpServletResponse response){
        //创建对象
        VerifyCode vc = new VerifyCode();
        //获取图片对象
        BufferedImage bi = vc.getImage();
        //获得图片的文本内容
        String text = vc.getText();
        // 将系统生成的文本内容保存到session中
        request.getSession().setAttribute("code", text);
        //向浏览器输出图片
        try {
            VerifyCode.output(bi, response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
